<template>
    <div class="rate">
        <span v-for="index in 5" :key="'star-' + index" class="star">
            <img class="xingxing" :src="getStarImage(index)" :alt="'评分' + index" />
        </span>
    </div>
</template>

<script>
export default {
    name: 'Rate',
    data() {
        return {
            currentRate: 0, // 当前评分
            hasHalfStar: false // 是否有半星
        }
    },
    props: {
        modelValue: {
            type: [Number, String],
            default: 0,
            validator: (value) => {
                // 验证传入的值是否有效
                const num = Number(value);
                return !isNaN(num) && num >= 0 && num <= 5;
            }
        }
    },
    methods: {
        getStarImage(index) {
            if (index <= Math.floor(this.currentRate)) {
                return 'https://www.kdxwindowfilm.com/banners/static/hong2.png'; // 整星
            } else if (index === Math.ceil(this.currentRate) && this.hasHalfStar) {
                return 'https://www.kdxwindowfilm.com/banners/static/honghalf.png'; // 半星
            } else {
                return 'https://www.kdxwindowfilm.com/banners/static/hong0.png'; // 空星（假设你有空星图片）
            }
        }
    },
    watch: {
        modelValue: {
            immediate: true,
            handler(newVal) {
                // 处理字符串转换为数字的逻辑
                if (typeof newVal === 'string') {
                    // 去除前后空格
                    const trimmedVal = newVal.trim();
                    // 如果是空字符串，设为0
                    if (trimmedVal === '') {
                        this.currentRate = 0;
                        this.hasHalfStar = false;
                        return;
                    }
                    // 尝试转换为数字
                    const num = Number(trimmedVal);
                    // 确保转换后的数字在0-5范围内
                    if (!isNaN(num)) {
                        this.currentRate = Math.min(5, Math.max(0, num));
                        this.hasHalfStar = num % 1 !== 0;
                    } else {
                        this.currentRate = 0;
                        this.hasHalfStar = false;
                    }
                } else {
                    // 已经是数字类型，直接使用（确保在0-5范围内）
                    this.currentRate = Math.min(5, Math.max(0, newVal));
                    this.hasHalfStar = newVal % 1 !== 0;
                }
            }
        }
    }
}
</script>

<style scoped lang="less">
.xingxing {
    width: 40px;
    display: block;
    margin: 0 2px;
}

.rate {
    display: inline-flex;
    margin-top: 5px;
    align-items: center;

    .star {
        display: inline-flex;
        align-items: center;
        justify-content: center;
    }
}
</style>